package com.lwl.blue.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lwl.blue.commont.base.*;
import com.lwl.blue.commont.enums.RoleTypeEnum;
import com.lwl.blue.commont.utils.UserContextUtil;
import com.lwl.blue.entity.Department;
import com.lwl.blue.entity.Users;
import com.lwl.blue.service.DepartmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/department")
@Slf4j
public class DepartmentController extends BaseController {
    @Autowired
    DepartmentService departmentService;

    /**
     * 分页查询
     *
     * @param pageParam
     * @return
     */
    @PostMapping("/pages")
    public PageResult<Department> pages(@RequestBody PageParam<Department> pageParam) {

        // 调用服务层分页查询方法
        JsonResult<Page<Department>> pages = departmentService.pages(pageParam);
        PageResult<Department> result = new PageResult<>();
        // 设置分页结果并返回
        return result.success(pages.getData().getTotal(), pages.getData().getRecords());
    }

    /**
     * 保存或更新部门信息
     *
     * @param department
     * @return
     */
    @PostMapping("/saveOrUpdate")
    public JsonResult saveOrUpdate(@RequestBody Department department) {
        // 检查当前用户是否有权限操作（只有ALL角色可以操作）
        if (RoleTypeEnum.ALL.getValue() != getUserInfo().getRoleType()) {
            return new JsonResult().error("没有操作权限");
        }
        // 构建查询条件，检查部门名是否已存在
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Department::getName, department.getName());
        // 只查询未删除的数据
        wrapper.eq("is_delete", 0);

        // 如果是更新操作，排除当前部门id
        if (null != department.getId()) {
            wrapper.lambda().notIn(Department::getId, department.getId());
        }
        // 查询是否存在相同部门名
        int count = departmentService.count(wrapper);
        if (count > 0) {
            // 抛出部门已存在异常
            throw new BizException(ErrorCode.DEPARTMENT_EXISTS_ERROR.getCode(), ErrorCode.DEPARTMENT_EXISTS_ERROR.getMsg());
        }
        // 设置创建/更新人信息
        setInsetOrUpdateUser(department);

        // 保存或更新用户信息
        departmentService.saveOrUpdate(department);
        return new JsonResult().success("请求成功");
    }

    @PostMapping("/delete/{id}")
    public JsonResult saveOrUpdate(@PathVariable(value = "id") Integer id) {
        // 检查当前用户是否有权限操作（只有ALL角色可以操作）
        if (RoleTypeEnum.ALL.getValue() != getUserInfo().getRoleType()) {
            return new JsonResult().error("没有操作权限");
        }
        // 获取需要删除的部门信息
        //Department department = departmentService.getById(id);

        // 物理删除部门
        //departmentService.removeById(id);

        // 逻辑删除部门
        departmentService.update(new UpdateWrapper<Department>().lambda()
                .set(Department::getIsDelete, Const.IS_DELETE_YES)  // 设置删除标志为1
                .set(Department::getUpdateUser, UserContextUtil.getUser().getUserName())  // 记录操作人
                .eq(Department::getId, id));
        return new JsonResult().success("请求成功");
    }
}
